package routers

import (
	"fmt"
	"net/http"
	"togethorGo/handler"
)

// Router : 路由
type Router struct {
	version string           //api 版本
	url     string           //映射路径
	handler http.HandlerFunc //http模块处理函数
	auth    bool             //是否需要校验
}

//HTTPAuthInterceptor : 用户登陆校验
func HTTPAuthInterceptor(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		username := r.Form.Get("username")
		// password := r.Form.Get("password")
		token := r.Form.Get("token")
		// fmt.Printf("username=%s password=%s \n", username, password)
		if !handler.IsTokenValid(username, token) {
			fmt.Printf("校验用户失败: %s\n", token)
			w.WriteHeader(http.StatusForbidden)
			return
		}
		h(w, r)
	}
}

// NewRouter : 构造Router
func NewRouter(v, url string, handler http.HandlerFunc, auth bool) Router {
	return Router{
		version: v,
		url:     url,
		handler: handler,
		auth:    auth,
	}
}

// InitRouter ： 初始化所有路由
func InitRouter() {

	allRouters := make([]Router, 0, 100)
	//合并所有路由
	allRouters = append(allRouters, UserRouters...)
	allRouters = append(allRouters, orderRouters...)
	for _, r := range allRouters {
		// fmt.Printf("aaaaa%s \n", r.url)
		if r.auth != true {
			http.HandleFunc("/"+r.version+r.url, r.handler)
		} else {
			http.HandleFunc("/"+r.version+r.url, HTTPAuthInterceptor(r.handler))
		}
	}
}
